import pandas as pd
from django.http import JsonResponse
from rest_framework.views import APIView
from app01 import models
from app01.woutils import user_jwt
from django.http import HttpResponse
from django import forms
from app01.models import PhonoManageInfo
from django.db.models import Q
from datetime import datetime
from django.utils import timezone
from datetime import datetime, timezone
import dateutil.parser
from datetime import datetime
from dateutil import parser
from django.utils import timezone
import pytz


class PhonoManForm(forms.ModelForm):
    class Meta:
        model = PhonoManageInfo
        # fields = '__all__'
        fields = ['project', 'phono', 'claid', 'username', 'remark', 'statu']


class phoneMange_api(APIView):
    #接口
    def get(self, request):
        #获取单条
        uid = request.query_params.get('id')
        if uid:
            # 查询单条数据
            try:
                data_obj = models.PhonoManageInfo.objects.filter(pk=uid).first()
                if data_obj is not None:
                    data = {
                        'code': 200,
                        'msg': '查询成功',
                        'data': {
                            'id': data_obj.pk,
                            'project': data_obj.project,
                            'phono': data_obj.phono,
                            'claid': data_obj.claid,
                            'username': data_obj.username,
                            'remark': data_obj.remark,
                            'statu': data_obj.statu,
                        }
                    }
                    return JsonResponse(data)
                else:
                    return JsonResponse({'code': 404, 'msg': '记录不存在', 'data': ''})
            except PhonoManageInfo.DoesNotExist:
                return JsonResponse({'code': 404, 'msg': '记录不存在', 'data': ''})
        else:
            # 获取页数参数
            try:
                page = int(request.query_params["page"])  # 获取get请求传递的参数 page
                pagesize = int(request.query_params["pagesize"])
            except Exception as e:
                page = 1
                pagesize = 10
            if page < 1:
                page = 1
            dic = {}
            
            filters = Q()
            username=request.query_params.get("username","")
            claid=request.query_params.get("claid","")
            phono=request.query_params.get("phono", "")
            project=request.query_params.get("project","")
            statu = request.query_params.get("statu", "")
            custom_date = request.query_params.get("custom_date", "")
            CreatedTime = request.query_params.getlist('CreatedTime[]', None)

            if username:
                dic['username__icontains'] = username    #username是需要搜索的字段名 __icontains为使用模糊搜索
            if phono:
                dic['phono__icontains'] = phono
            if claid:
                dic['claid__icontains'] = claid
            if project:
                dic['project__icontains'] = project
            if statu:
                dic['statu__icontains'] = statu
            if custom_date:
                dic['custom_date__icontains'] = custom_date

            if len(CreatedTime) == 2:
                try:
                    # 去除毫秒部分
                    # start = dateutil.parser.isoparse(CreatedTime[0])
                    # start_date = formatted_dt_str = start.strftime("%Y-%m-%d %H:%M:%S")
                    start = CreatedTime[0].replace("T", " ").replace(".000Z", "").replace("+", "")
                    start_date = datetime.strptime(start, "%Y-%m-%d %H:%M:%S")
                    # 解析日期
                    end = dateutil.parser.isoparse(CreatedTime[1])
                    end_date = end.strftime("%Y-%m-%d %H:%M:%S")
                    # print(start_date, end_date)
                    
                    # # 确保结束时间包含整天
                    end_date = datetime.strptime(end_date, "%Y-%m-%d %H:%M:%S") + timezone.timedelta(days=1)
                    # print(end_date)
                    # 使用utc时间
                    # start_date_str = timezone.make_aware(datetime.strptime(start_date, "%Y-%m-%d %H:%M:%S"), timezone=timezone.utc)
                    # end_date_str = timezone.make_aware(end_date, timezone=timezone.utc)
                    # print(start_date_str, end_date_str)
                
                # 应用过滤条件
                    dic['CreatedTime__range'] = (start_date, end_date)
                    
                except ValueError:
                    print("错误日志")
            

            # if username:
            #     filters &= Q(username__icontains=username)
            # if claid:
            #     filters &= Q(claid__icontains=claid)
            # if phono:
            #     filters &= Q(phono__icontains=phono)
            # if project:
            #     filters &= Q(project__icontains=project)
            # if statu:
            #     filters &= Q(statu=statu)
            #计算分页值
            #计算每一页显示内容的范围
            start_page = page * pagesize -pagesize
            end_page = page * pagesize
            # for key, value in dic.items():
            #     print(key, value)
        
            #查询数据库 获取数据        .order_by('-id')是按id倒序进行排列
            #datas = models.PhonoManageInfo.objects.filter(**dic).order_by('-id')[start_page:end_page].values()   #从数据库中提取数据
            datas = models.PhonoManageInfo.objects.filter(**dic).order_by('-id')[start_page:end_page].values()   #从数据库中提取数据
            data_list = []
            for item in datas:
                item['CreatedTime'] = item['CreatedTime'].strftime("%Y-%m-%d %H:%M:%S")
                item['UpdatedTime'] = item['UpdatedTime'].strftime("%Y-%m-%d %H:%M:%S")
                data_list.append(item)
            # print(datas)
            #查询数据条数
            total = models.PhonoManageInfo.objects.filter(**dic).count()
        
            #制作返回给前端的json
            data = {
                "code": 200,
                "msg": "查询成功",
                "total": total,
                "data": data_list
            }
            return JsonResponse(data)          #以json格式返回数据


    def delete(self,request):
        '''删除数据'''
        #获取需要删除的id
        ids = request.query_params.get("id","")
        if ids == "":
            data = {'code': 503,"msg":"删除参数为空", 'data':""}
            return JsonResponse(data)
        #将字符串切割为列表
        ids = ids.split(",")
        ids_int = []
        for i in ids:
            if i == "":
                continue
            ids_int.append(int(i))  #将id转换为数字类型 然后添加到新的列表中

        #id__in为 根据id字段 传入一个列表 批量查询需要删除的数据
        Obj=models.PhonoManageInfo.objects.filter(id__in=ids_int)
        #检测数据是否存在
        if not Obj.exists():
            data = {'code': 503, "msg": "未找到数据", 'data': ""}
            return JsonResponse(data)
        #删除查询到的数据
        Obj.delete()
        data = {'code': 200, "msg": "删除成功", 'data': ""}
        return JsonResponse(data)


    def post(self, request):
        form = PhonoManForm(request.data)
        if form.is_valid():
            form.save()
            data = {'code': 200, "msg": "新增成功", 'data': form.data}
        else:
            data = {'code': 503, "msg": "新增失败", 'data': form.errors}
        return JsonResponse(data)

    def put(self, request):
        uid = request.data.get("id")
        form_data = request.data.copy()
        form_data.pop('id', None)
        try:
            instance = PhonoManageInfo.objects.get(pk=uid)
        except PhonoManageInfo.DoesNotExist:
            return JsonResponse({'code': 404, "msg": "记录不存在", 'data': ""})
        form = PhonoManForm(form_data, instance=instance)
        if form.is_valid():
            form.save()
            return JsonResponse({'code': 200, "msg": "修改成功", 'data': form.data})
        else:
            errors = form.errors  # 获取表单验证错误
            print(errors)
            return JsonResponse({'code': 400, "msg": "数据验证失败", 'data': errors})